<template>
  <el-dialog
    class="new-reference-dialog"
    :title="$t('flyparam.select_reference_table')"
    v-bind="$attrs"
    @open="handleOpen"
    v-on="$listeners"
    @closed="handleClose"
  >
    <div v-loading="loading" class="text-center px-3 new-reference-container">
      <el-row :gutter="10">
        <el-col :span="8">
          <div class="list-wrapper">
            <div class="list">
              <div class="list-header">
                <h5 class="list-header-name">
                  <svg-icon icon-class="sub-profile" class-name="mr-2" />{{ $t('flyparam.sub_profile_type') }}
                </h5>
              </div>
              <div class="list-cards">
                <template>
                  <el-scrollbar style="height: 100%">
                    <a
                      v-show="!showSubProfileInput"
                      class="list-card text-center"
                      @click.prevent="() => showSubProfileInput = true"
                    >
                      <div class="list-card-details">
                        <i class="icon-add el-icon-plus" />
                        <span>{{ $t('common.add') }}</span>
                      </div>
                    </a>
                    <div v-show="showSubProfileInput" class="card-composer">
                      <el-input ref="subProfileInput" v-model="subProfileValue" size="small" :maxlength="64" />
                      <div class="controls">
                        <div class="controls-section">
                          <el-button
                            type="primary"
                            size="small"
                            @click="() => newTable('1')"
                          >{{ $t('common.confirm') }}</el-button>
                          <a
                            href="#"
                            class="cancel-button"
                            @click.prevent="() => showSubProfileInput = false"
                          >
                            <i class="el-icon-close" @click="cancel('subProfileInput')" />
                          </a>
                        </div>
                      </div>
                    </div>
                    <template v-if="subProfileTables.length > 0">
                      <a
                        v-for="table in subProfileTables"
                        :key="table.id"
                        class="list-card text-center"
                        @click="confirm(table)"
                      >
                        <div class="list-card-details">{{ table.name }}</div>
                      </a>
                    </template>
                    <div v-else class="no-data">{{ $t('common.no_data') }}</div>
                  </el-scrollbar>
                </template>
              </div>
            </div>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="list-wrapper">
            <div class="list">
              <div class="list-header">
                <h5 class="list-header-name">
                  <svg-icon icon-class="label-object" class-name="mr-2" />{{ $t('flyparam.list_object_type') }}
                </h5>
              </div>
              <div class="list-cards">
                <template>
                  <el-scrollbar style="height: 100%">
                    <a
                      v-show="!showListObjectInput"
                      class="list-card text-center"
                      @click.prevent="() => showListObjectInput = true"
                    >
                      <div class="list-card-details">
                        <i class="icon-add el-icon-plus" />
                        <span>{{ $t('common.add') }}</span>
                      </div>
                    </a>
                    <div v-show="showListObjectInput" class="card-composer">
                      <el-input ref="listObjectInput" v-model="listObjectValue" size="small" :maxlength="64" />
                      <div class="controls">
                        <div class="controls-section">
                          <el-button type="primary" size="small" @click="() => newTable('2')">
                            {{
                              $t('common.confirm')
                            }}
                          </el-button>
                          <a
                            href="#"
                            class="cancel-button"
                            @click.prevent="() => showListObjectInput = false"
                          >
                            <i class="el-icon-close" @click="cancel('listObjectInput')" />
                          </a>
                        </div>
                      </div>
                    </div>
                    <template v-if="listObjectTables.length > 0">
                      <a
                        v-for="table in listObjectTables"
                        :key="table.id"
                        class="list-card text-center"
                        @click="confirm(table)"
                      >
                        <div class="list-card-details">{{ table.name }}</div>
                      </a>
                    </template>
                    <div v-else class="no-data">{{ $t('common.no_data') }}</div>
                  </el-scrollbar>
                </template>
              </div>
            </div>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="list-wrapper">
            <div class="list">
              <div class="list-header">
                <h5 class="list-header-name">
                  <svg-icon icon-class="label-value" class-name="mr-2" />{{ $t('flyparam.list_value_type') }}
                </h5>
              </div>
              <div class="list-cards">
                <template>
                  <el-scrollbar style="height: 100%">
                    <a
                      v-show="!showListValueInput"
                      class="list-card text-center"
                      @click.prevent="() => showListValueInput = true"
                    >
                      <div class="list-card-details">
                        <i class="icon-add el-icon-plus" />
                        <span>{{ $t('common.add') }}</span>
                      </div>
                    </a>
                    <div v-show="showListValueInput" class="card-composer">
                      <el-input ref="listValueInput" v-model="listValue" size="small" :maxlength="64" />
                      <div class="controls">
                        <div class="controls-section">
                          <el-button type="primary" size="small" @click="() => newTable('3')">
                            {{
                              $t('common.confirm')
                            }}
                          </el-button>
                          <a
                            href="#"
                            class="cancel-button"
                            @click.prevent="() => showListValueInput = false"
                          >
                            <i class="el-icon-close" @click="cancel('listValueInput')" />
                          </a>
                        </div>
                      </div>
                    </div>
                    <template v-if="listValueTables.length > 0">
                      <a
                        v-for="table in listValueTables"
                        :key="table.id"
                        class="list-card text-center"
                        @click="confirm(table)"
                      >
                        <div class="list-card-details">{{ table.name }}</div>
                      </a>
                    </template>
                    <div v-else class="no-data">{{ $t('common.no_data') }}</div>
                  </el-scrollbar>
                </template>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>
  </el-dialog>
</template>

<script>
import { createNewTable, getReferenceTable } from '@/api/parameter'

function validateTableName(rule, value, callback) {
  if (value) {
    if (/^\s+$/.test(value)) {
      // 纯空格报错
      callback(new Error(this.$t('flyparam.invalid_input')))
    }
  }
  callback()
}

export default {
  name: 'NewReferenceDialog',
  props: {
    component: Object,
    tableId: String,
    templateId: String
  },
  data() {
    return {
      showSubProfileInput: false,
      showListObjectInput: false,
      showListValueInput: false,
      subProfileValue: '',
      listObjectValue: '',
      listValue: '',
      loading: false,
      tables: []
    }
  },
  computed: {
    subProfileTables() {
      return (
        (this.tables && this.tables.filter((table) => table.tableType === 1)) ||
        []
      )
    },
    listObjectTables() {
      return (
        (this.tables && this.tables.filter((table) => table.tableType === 2)) ||
        []
      )
    },
    listValueTables() {
      return (
        (this.tables && this.tables.filter((table) => table.tableType === 3)) ||
        []
      )
    }
  },
  methods: {
    fetchReferenceTable() {
      this.loading = true
      getReferenceTable(this.templateId, this.tableId)
        .then((data) => {
          this.tables = data
        })
        .catch((err) => {
          this.$message.error(err)
        })
        .finally(() => {
          this.loading = false
        })
    },
    handleOpen() {
      this.fetchReferenceTable()
    },
    requestCreateTable(tableName, type) {
      return new Promise((resolve, reject) => {
        createNewTable({ tableType: type, tableName }, this.templateId)
          .then(() => {
            this.$emit('update-table', this.tableId)
            resolve()
          })
          .catch((err) => {
            reject(err)
          })
      })
    },
    confirm(table) {
      this.component.table = {
        id: table.id,
        tableType: table.tableType
      }
      this.$emit('update:model-value', false)
      this.$emit('confirm', table, this.tableId)
    },
    async newTable(type) {
      let tableName = ''
      switch (type) {
        case '1':
          tableName = this.subProfileValue
          break
        case '2':
          tableName = this.listObjectValue
          break
        case '3':
          tableName = this.listValue
          break
      }
      if (!tableName || /^\s+$/.test(tableName)) {
        return this.$message.error(this.$t('flyparam.invalid_input'))
      }

      if (tableName.length > 64) {
        return this.$message.error(this.$t('flyparam.length_exceeds'))
      }
      try {
        this.loading = true
        await this.requestCreateTable(tableName.trim(), type)
        this.loading = false

        switch (type) {
          case '1':
            this.subProfileValue = ''
            this.showSubProfileInput = false
            break
          case '2':
            this.listObjectValue = ''
            this.showListObjectInput = false
            break
          case '3':
            this.listValue = ''
            this.showListValueInput = false
        }
        this.fetchReferenceTable()
        this.$message.success(this.$t('common.operated_successfully'))
      } catch (e) {
        this.loading = false
        this.$message.error(e)
      }
    },
    cancel(ref) {
      this.$refs[ref].clear()
    },
    handleClose() {
      Object.assign(this.$data, this.$options.data())
    }
  }
}
</script>

<style lang="scss" scoped>
@import '@/styles/mixin.scss';
@include listCard;

.new-reference-container {
  padding: 20px 10px;

  .list-cards {
    height: 300px;
    padding: 0 4px;
  }

  .no-data {
    height: 300px;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .list-card {
    margin: 0 2px 8px;
  }

  .list-header-name {
    display: flex;
    align-items: center;
  }

  ::v-deep.el-scrollbar__wrap {
    overflow-x: hidden;
  }

  ::v-deep.el-input__inner:focus {
    box-shadow: none;
  }
}
</style>
